#include "Monomial.h"
#include <math.h>
using namespace std;

// 重载流插入运算符
istream &operator>>(istream &in, Monomial &monomial)
{
    int x_index, p_index;
    string input;
    in >> input;
    int l = input.length();
    for (int i = 0; i < l; i++)
    {
        if (input[i] == 'x')
            x_index = i;
        if (input[i] == '^')
            p_index = i;
    }
    string c = input.substr(0, x_index);
    string d = input.substr(p_index + 1, l - p_index - 1);
    monomial.coe = stoi(c);
    monomial.deg = stoi(d);
    return in;
}

// 构造函数
Monomial::Monomial(int coe, int deg)
{
    this->coe = coe;
    this->deg = deg;
    if (this->coe == 0)
    {
        this->deg = 0;
    }
}
Monomial::Monomial()
{
    coe = 0;
    deg = 0;
}

// 重载四则运算符
Monomial Monomial::operator+(const Monomial &y)
{
    if (this->coe + y.coe == 0)
    {
        return Monomial(0, 0);
    }
    else
    {
        return Monomial(this->coe + y.coe, this->deg);
    }
}

Monomial Monomial::operator-(const Monomial &y)
{
    if (this->coe - y.coe == 0)
    {
        return Monomial(0, 0);
    }
    else
    {
        return Monomial(this->coe - y.coe, this->deg);
    }
}

Monomial Monomial::operator*(const Monomial &y)
{
    if (this->coe * y.coe == 0)
    {
        return Monomial(0, 0);
    }
    else
    {
        return Monomial(this->coe * y.coe, this->deg + y.deg);
    }
}

Monomial Monomial::operator/(const Monomial &y)
{
    if (this->coe / y.coe == 0)
    {
        return Monomial(0, 0);
    }
    else
    {
        return Monomial(this->coe / y.coe, this->deg - y.deg);
    }
}

Monomial Monomial::derive()
{
    return Monomial(coe * deg, deg - 1);
}

int Monomial::definite_integral(const int a, const int b)
{
    return coe / (deg + 1) * (pow(b, deg + 1) - pow(a, deg + 1));
}

ostream &
operator<<(ostream &out, const Monomial &x)
{
    out << x.coe << "x^" << x.deg << endl;
    return out;
}

int Monomial::get_val(int par)
{
    return this->coe * (pow(par, this->deg));
}